<template>
	<view class="container">
		<view class="ipt" style="margin-top: 30rpx;">
			<text>手机号码</text>
			<input maxlength="11" type="number" placeholder="请输入手机号码" v-model="mobile" />
		</view>
		<view class="code-container ipt">
			<view>
				<text>验证码</text>
				<view v-if="!checkCodeFlag" @click="handleSendCode">发送验证码</view>
				<view v-if="checkCodeFlag" style="color: #9B9B9B;border: none;font-size: 14px;">已发送（{{ count }}S）</view>
			</view>
			<input maxlength="6" type="number" placeholder="请输入验证码" v-model="checkCode" />
		</view>
		<view class="submit" @click="handleConfirmBindMobile">确认绑定</view>
		<view class="modal" :class="modalFlag ? 'show' : ''">
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				modalFlag: false, // 默认模态框为关闭状态
				openId: '', // 用户openId
				mobile: '', //手机号码
				checkCodeFlag: false, // 判断是否发生验证码
				checkCode: "", // 手机验证码
				count: 60, // 验证码数字判断
				id: '', //第三方授权id
				loginType: 1, //1微信登录,2苹果登陆
				oldCheckCode: '', //旧的验证码，防止误触登录
				inviteCode: '',
				register_obj: {}, //微信或苹果的信息
			};
		},
		methods: {
			// 验证手机号格式是否正确
			checkLoginNameFormat(mobile) {
				let reg = /^[1][3456789][0-9]{9}$/
				if (!reg.test(mobile)) {
					uni.showToast({
						title: '手机号格式不正确',
						icon: 'none'
					})
					return false
				}
				return true
			},
			// 发送验证码
			async handleSendCode() {
				if (!this.checkLoginNameFormat(this.mobile)) return
				this.checkCodeFlag = true

				let res = await this.$fetch(this.$api.mobile_verification_code, {
					length: 6,
					mobile: this.mobile
				}, 'POST')
				if (res.code) return uni.showToast({
					title: res.msg,
					icon: 'none'
				})
				this.timer = setInterval(() => {
					if (this.count === 0) {
						clearInterval(this.timer)
						this.checkCodeFlag = false
						this.count = 60
					}
					this.count = --this.count
				}, 1000)
			},

			// 点击确认绑定
			async handleConfirmBindMobile() {
				console.log('获取区域绑定手机region前6', uni.getStorageSync('region').slice(0, 6))
				if (!this.checkCode.trim()) return uni.showToast({
					title: '请先输入验证码~',
					icon: 'none'
				})
				if (!this.mobile.trim()) return uni.showToast({
					title: '请输入手机号码~',
					icon: 'none'
				})
				// 防止误触登陆按钮
				// if(this.oldCheckCode == this.checkCode) return uni.showToast({ title: '请输入新验证码~', icon: 'none' })
				// this.oldCheckCode = this.checkCode

				var pinf = plus.push.getClientInfo()
				var cid = pinf.clientid //客户端标识  
				let adcode = uni.getStorageSync('region').slice(0, 6)
				let obj = {
					// avatarUrl: this.register_obj.avatar, 
					checkCode: this.checkCode, // 验证码
					cid: cid, //客户端标识  
					id: this.id,
					loginType: this.loginType,
					mobile: this.mobile,
					nickName: this.register_obj.userName,
					adcode: adcode,
				}
				console.log('信息', obj)
				// return
				let res = await this.$fetch(this.$api.register, obj, 'POST') //

				if (res.code) return uni.showToast({
					title: res.msg,
					icon: 'none'
				})
				uni.setStorageSync('token', res.data.token)
				if (this.register_obj.sex) {
					// 微信性别0保密1男2女，找零工0男1女
					this.sex = this.register_obj.sex == 1 ? 0 : 1
					// this.upd_user(this.sex)
				}

				uni.showToast({
					title: '登录成功~',
					icon: 'none'
				})
				// 是否已注册
				this.getUserInfo()
				this.getSetting()
			},
			// 获取用户当前的经纬度
			get_current_location() {
				uni.getLocation({
					// #ifdef MP-WEIXIN || MP-TOUTIAO
					type: 'gcj02',
					// #endif
					success: (res) => {
						uni.setStorageSync('location', [res.latitude, res.longitude])
						this.getAdcode(res.latitude, res.longitude)
					}
				})
			},
			//微信获取地址
			wx_get_current_location() {
				uni.authorize({
					scope: 'scope.userLocation',
					success: () => {
						wx.startLocationUpdate();
						wx.onLocationChange(res => {
							const latitude = res.latitude;
							const longitude = res.longitude;
							this.getAdcode(latitude, longitude)
						})
					},
					fail: () => {
						//this.getSetting()
					}
				})
			},
			// 判断用户是否授权
			getSetting() {
				uni.getSetting({
					success: (res) => {
						if (res.authSetting['scope.userLocation'] != undefined && res.authSetting[
								'scope.userLocation'] != true) { //非初始化进入该页面,且未授权
							uni.showModal({
								title: '是否授权当前位置',
								content: '需要获取您的地理位置，请确认授权，否则无法获取您所需数据',
								success: res => {
									if (res.cancel) {
										uni.showToast({
											title: '授权失败',
											icon: 'none',
											duration: 1000
										})
									} else if (res.confirm) {
										this.openSet()
									}
								}
							})
						} else {
							// #ifdef MP-WEIXIN
							this.wx_get_current_location()
							// #endif
						}
					}
				})
			},
			/* 打开设置 */
			openSet() {
				uni.openSetting({
					success: dataAu => {
						if (dataAu.authSetting[
								"scope.userLocation"] ==
							true) {
							uni.showToast({
								title: '授权成功',
								icon: 'success',
								duration: 1000
							})
							// #ifdef MP-WEIXIN
							this.wx_get_current_location()
							// #endif
						} else {
							uni.showToast({
								title: '授权失败',
								icon: 'none',
								duration: 1000
							})
						}
					}
				})
			},
			// 由经纬度查询街道的行政代码
			getAdcode(lat, lng) {
				uni.request({
					url: 'https://restapi.amap.com/v3/geocode/regeo?parameters',
					data: {
						key: 'd73cc951a96637a251a9a2446b48ce9c',
						location: lng + ',' + lat
					},
					success: res => {
						let region = res.data.regeocode.addressComponent.towncode.slice(0, 9)
						uni.setStorageSync('region', region)
						console.log('获取区域region', uni.getStorageSync('region'))
						// #ifdef MP-WEIXIN
						wx.stopLocationUpdate();
						wx.offLocationChange();
						// #endif
						if (uni.getStorageSync('token')) {
							this.upd_user(lat, lng, region, this.sex) //修改	
						}
					}
				})
			},
			//更新用户位置
			async upd_user(lat, lng, region, sex) {
				//经纬度保留6位小数
				lat = lat.toFixed(6)
				lng = lng.toFixed(6)
				region = region.slice(0, 9)
				console.log('更新用户位置', lat, lng, region)
				let res = await this.$fetch(this.$api.upd_user, {
					lat: lat,
					lng: lng,
					region: region,
					sex: sex
				}, 'POST')
				console.log('更新用户位置res', res)
			},

			// 获取当前用户信息
			async getUserInfo() {
				let res = await this.$fetch(this.$api.get_current_user, {}, 'GET')
				if (res.code) return uni.showToast({
					title: res.msg,
					icon: 'none'
				})
				console.log('用户', res.data.userType)
				// 注册用户
				if (res.data.userType == '-1') {
					console.log('未注册')
					setTimeout(() => {
						uni.reLaunch({
							url: '/pages/select-identity/select-identity'
						})
					}, 600)
					// 登录用户
				} else if (res.data.noviceguide == 0 && uni.getStorageSync("first")) {
					// <!-- 此处改动， 154-158
					// 第一次登录  设置个人信息
					uni.setStorageSync('first', false)
					setTimeout(() => {
						uni.reLaunch({
							url: '/pages/userifo-supplement/userifo-supplement'
						})
					}, 600)
				} else {
					console.log('已经注册')
					uni.setStorageSync("level", res.data.user.level) //用户等级
					setTimeout(() => {
						uni.switchTab({
							url: '/pages/index/index'
						})
					}, 600)
				}
			},


		},
		onLoad(options) {
			this.id = options.id
			this.loginType = options.loginType
			this.register_obj = uni.getStorageSync('register_obj')
		}
	}
</script>

<style lang="less" scoped>
	.container {
		overflow: hidden;

		&>view.ipt {
			background: #FFFFFF;
			padding: 30rpx;
			display: flex;
			justify-content: space-between;
			align-items: center;

			input {
				font-size: 14px;
				text-align: right;
				background: transparent;
			}
		}

		&>.code-container {
			position: relative;

			&::before {
				content: "";
				position: absolute;
				width: 720rpx;
				height: 1px;
				left: 30rpx;
				top: 0;
				background: #F3F3F3;
			}

			&>view:first-child {
				display: flex;
				align-items: center;

				text {
					margin-right: 30rpx;
				}

				view {
					padding: 8rpx;
					// border: 1px solid #FCC928;
					border-radius: 4px;
					font-size: 10px;
					color: #F39B19;
				}
			}
		}

		&>.submit {
			position: fixed;
			bottom: 0;
			left: 0;
			background: #FCC928;
			width: 100vw;
			height: 100rpx;
			padding: 0;
			justify-content: center;
			display: flex;
			align-items: center;

			&:active {
				opacity: 0.7;
			}
		}
	}

	.modal {
		position: fixed;
		top: 0;
		right: 0;
		bottom: 0;
		left: 0;
		z-index: 1110;
		opacity: 0;
		outline: 0;
		text-align: center;
		-ms-transform: scale(1.185);
		transform: scale(1.185);
		backface-visibility: hidden;
		perspective: 2000upx;
		background: rgba(0, 0, 0, 0.6);
		transition: all 0.3s ease-in-out 0s;
		pointer-events: none;

		&.show {
			opacity: 1;
			transition-duration: 0.3s;
			-ms-transform: scale(1);
			transform: scale(1);
			overflow-x: hidden;
			overflow-y: auto;
			pointer-events: auto;
		}

		.main {
			position: fixed;
			left: 50%;
			top: 50%;
			transform: translate(-50%, -50%);
			width: 516rpx;
			border-radius: 10rpx;
			padding: 30rpx;
			background: #FFFFFF;
			position: relative;

			image {
				width: 516rpx;
				height: 516rpx;
			}

			.text {
				color: #848484;
				margin-top: 5rpx;
			}

			.handle {
				color: #45b6e0;
				margin-top: 30rpx;
				line-height: 14px;
			}

			&::before {
				content: "";
				position: absolute;
				width: 100%;
				height: 1px;
				background: #f7f7f7;
				bottom: calc(60rpx + 14px);
				left: 0;
			}
		}
	}
</style>
